﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Windows.Forms;
using AppAcc.Models;
using AppAcc.Views.DanhMuc;

namespace AppAcc.Views.KTTSCD
{
    public partial class FormTangTaiSanThemCT : DevComponents.DotNetBar.RibbonForm
    {
        //private AppAccContext db = new AppAccContext();
        private PhanMenKeToanEntities1 db = new PhanMenKeToanEntities1();
        private int indexrow = 0;
        private bool kt = false;
        public FormTangTaiSanThemCT()
        {
            InitializeComponent();
        }
        #region Event
        private void FormTangTaiSanThemCT_Load(object sender, EventArgs e)
        {
            FillDataGridView();
            FillDataChungTu();
            GetMaPhieuChungTu();
            KiemTra();
            kt = true;
        }
        private void BttThemTaiSan_Click(object sender, EventArgs e)
        {
            var f = new FormTaiSan();
            f.ShowDialog();
        }
        private void bttThemMoi_Click(object sender, EventArgs e)
        {
            Reset();
        }

        private void bttLuu_Click(object sender, EventArgs e)
        {
            CreatePhieuTangTSCD();
            //Chuyen qua edit
        }

        private void bttLuu_Thoat_Click(object sender, EventArgs e)
        {
            CreatePhieuTangTSCD();
            this.Close();
        }

        private void bttLuu_ThemMoi_Click(object sender, EventArgs e)
        {
            CreatePhieuTangTSCD();
            Reset();
        }

        private void bttInChungTu_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Chưa code");
        }

        private void bttThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cbbNhaCungCap_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void txtNoiDung_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void dtiNgayChungTu_ValueChanged(object sender, EventArgs e)
        {
            KiemTra();
        }
        private void cbbNhanVien_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTra();
        }
        private void dtiNgayLapPhieu_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }
        private void dgvPhieuTSCDCT_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right) return;
            var ht = dgvPhieuTSCDCT.HitTest(e.X, e.Y);
            var rowindex = ht.RowIndex;// get id chi tiet phieu tang tscd
            indexrow = rowindex;
            if (ht.ColumnIndex != -1 && ht.RowIndex != -1)
            {
                //New menu strip 
                var Menu = new ContextMenuStrip();
                var chen = new ToolStripMenuItem("Chèn (Ins)");//new button
                chen.MouseDown += new MouseEventHandler(CmsChenDong_Click);// add event to button
                var xoa = new ToolStripMenuItem("Xóa (Del)");
                xoa.MouseDown += new MouseEventHandler(CmsXoaDong_Click);
                Menu.Items.AddRange(new ToolStripItem[] { chen });//add button to menu strip
                Menu.Items.AddRange(new ToolStripItem[] { xoa });
                //add menu to datagridview
                dgvPhieuTSCDCT.ContextMenuStrip = Menu;
            }
            else
                dgvPhieuTSCDCT.ContextMenuStrip = null;
        }
        private void CmsChenDong_Click(object sender, EventArgs e)
        {
            var dgwr = new DataGridViewRow();
            dgvPhieuTSCDCT.Rows.Insert(indexrow, dgwr);
        }
        private void CmsXoaDong_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow r in dgvPhieuTSCDCT.Rows)
            {
                if (!r.IsNewRow)
                {
                    dgvPhieuTSCDCT.Rows.RemoveAt(r.Index);
                }
            }
        }
        private void bttThemMoiNhaCungCap_Click(object sender, EventArgs e)
        {
            var f = new FormDoiTac();
            f.ShowDialog();
        }

        private void bttThemMoiNhanVien_Click(object sender, EventArgs e)
        {
            var f = new FormNhanVien();
            f.ShowDialog();
        }

        private void dgvPhieuTSCDCT_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (kt == true)
            {
                KiemTra();
                UpdateAmount(e.ColumnIndex);
            }

        }
        #endregion Event
        #region Metho
        void GetMaPhieuChungTu()
        {
            var a = db.ChungTus.Count(t => t.TrangThai == 3);
            var mact = "PT" + (a + 1).ToString();
            txtSoChungTu.Text = mact;
            txtSoChungTu.Enabled = false;
            dtiNgayChungTu.Value = DateTime.Now;
            dtiNgayLapPhieu.Value = DateTime.Now;
        }

        void KiemTra()
        {
            if (txtNoiDung.Text != "" && Convert.ToInt32(cbbNhaCungCap.SelectedValue) != 0 && Convert.ToInt32(cbbNhanVien.SelectedValue) != 0 && dgvPhieuTSCDCT.RowCount > 1 && dtiNgayChungTu.Value.ToString().Length > 0 && dtiNgayLapPhieu.Value.ToString().Length > 0)
            {
                bttInChungTu.Enabled = true;
                bttLuu.Enabled = true;
                bttLuu_ThemMoi.Enabled = true;
                bttLuu_Thoat.Enabled = true;
            }
            else
            {
                bttInChungTu.Enabled = false;
                bttLuu.Enabled = false;
                bttLuu_ThemMoi.Enabled = false;
                bttLuu_Thoat.Enabled = false;
            }
        }

        private void FillDataChungTu()
        {
            cbbNhaCungCap.DataSource = db.DoiTacs.Where(t => t.NhomDoiTacId == 1).ToList();
            cbbNhaCungCap.DisplayMember = "TenDoiTac";
            cbbNhaCungCap.ValueMember = "Id";

            cbbNhanVien.DataSource = db.NhanViens.ToList();
            cbbNhanVien.DisplayMember = "TenNhanVien";
            cbbNhanVien.ValueMember = "Id";
        }
        private void FillDataGridView()
        {
            var n = dgvPhieuTSCDCT.Columns["TaiKhoanNo"] as DataGridViewComboBoxColumn;
            if (n != null)
            {
                n.DataSource = db.TaiKhoans.ToList();
                n.DisplayMember = "Id";
                n.ValueMember = "Id";
            }

            var c = dgvPhieuTSCDCT.Columns["TaiKhoanCo"] as DataGridViewComboBoxColumn;
            if (c != null)
            {
                c.DataSource = db.TaiKhoans.ToList();
                c.DisplayMember = "Id";
                c.ValueMember = "Id";
            }

            var n1 = dgvPhieuTSCDCT.Columns["NhomThueHangHoaId"] as DataGridViewComboBoxColumn;
            if (n1 != null)
            {
                n1.DataSource = db.NhomThueHangHoas.Where(t => t.LoaiThue == 2).ToList();
                n1.DisplayMember = "TenThue";
                n1.ValueMember = "Id";
            }

            var n2 = dgvPhieuTSCDCT.Columns["PhongBanId"] as DataGridViewComboBoxColumn;
            if (n2 != null)
            {
                n2.DataSource = db.PhongBans.ToList();
                n2.DisplayMember = "TenPhongBan";
                n2.ValueMember = "Id";
            }

            var n3 = dgvPhieuTSCDCT.Columns["TaiSanId"] as DataGridViewComboBoxColumn;
            if (n3 == null) return;
            n3.DataSource = db.TaiSans.ToList();
            n3.DisplayMember = "TenTaiSan";
            n3.ValueMember = "Id";
        }
        void CreatePhieuTangTSCD()
        {
            var pt = new ChungTu();
            pt.Id = txtSoChungTu.Text;
            pt.SoChungTuGoc = txtSoChungTuGoc.Text;
            pt.NgayChungTu = dtiNgayChungTu.Value;
            pt.NgayLapPhieu = dtiNgayLapPhieu.Value;
            pt.NhanVienId = Convert.ToInt32(cbbNhanVien.SelectedValue);
            pt.DoiTacId = Convert.ToInt32(cbbNhaCungCap.SelectedValue);
            pt.NoiDung = txtNoiDung.Text;
            pt.TrangThai = 3;
            int co = 1;
            decimal soTienNo = 0;
            decimal soTienCo = 0;
            pt.TongTien = 0;
            var kt = true;
            foreach (DataGridViewRow item in dgvPhieuTSCDCT.Rows)
            {
                if (co < dgvPhieuTSCDCT.RowCount)
                {
                    var ct = new ChungTuChiTiet();
                    ct.ChungTuId = pt.Id;
                    if (item.Cells["TaiKhoanNo"].Value != null && item.Cells["TaiKhoanNo"].Value.ToString().Length > 0)
                    {
                        ct.TaiKhoanNo = item.Cells["TaiKhoanNo"].Value.ToString();
                    }
                    else if (item.Cells["TaiKhoanCo"].Value != null && item.Cells["TaiKhoanCo"].Value.ToString().Length > 0)
                    {
                        ct.TaiKhoanCo = item.Cells["TaiKhoanCo"].Value.ToString();
                    }
                    if (item.Cells["TaiSanId"].Value != null && item.Cells["TaiSanId"].Value.ToString().Length > 0)
                    {
                        ct.TaiSanId = Convert.ToInt32(item.Cells["TaiSanId"].Value);
                    }
                    else
                    {
                        ct.TaiSanId = null;
                    }
                    if (item.Cells["SoTien"].Value != null && item.Cells["SoTien"].Value.ToString().Length > 0)
                    {
                        ct.SoTien = Convert.ToDecimal(item.Cells["SoTien"].Value);
                    }
                    else
                    {
                        ct.SoTien = null;
                    }
                    if (item.Cells["PhongBanId"].Value != null && item.Cells["PhongBanId"].Value.ToString().Length > 0)
                    {
                        ct.PhongBanId = Convert.ToInt32(item.Cells["PhongBanId"].Value);
                    }
                    else
                    {
                        ct.PhongBanId = null;
                    }
                    if (item.Cells["NhomThueHangHoaId"].Value != null && item.Cells["NhomThueHangHoaId"].Value.ToString().Length > 0)
                    {
                        ct.NhomThueHangHoaId = Convert.ToInt32(item.Cells["NhomThueHangHoaId"].Value);
                    }
                    else
                    {
                        ct.NhomThueHangHoaId = null;
                    }
                    if (item.Cells["DienGiai"].Value != null && item.Cells["DienGiai"].Value.ToString().Length > 0)
                    {
                        ct.DienGiai = item.Cells["DienGiai"].Value.ToString();
                    }
                    else
                    {
                        ct.DienGiai = null;
                    }
                    if (ct.TaiKhoanNo != null)
                    {
                        soTienNo += Convert.ToDecimal(ct.SoTien);
                    }
                    else if (ct.TaiKhoanCo != null)
                    {
                        soTienCo += Convert.ToDecimal(ct.SoTien);
                    }
                    co++;
                    if (ct.TaiSanId != null)
                    {
                        var ts = db.TaiSans.Find(ct.TaiSanId);
                        ts.TrangThai = 1;
                        ts.GiaTriKhauHao = Convert.ToDecimal(ct.SoTien);
                        db.Entry(ts).State = EntityState.Modified;
                    }
                    db.ChungTuChiTiets.Add(ct);
                }
            }
            pt.TongTien += soTienCo;
            if (soTienCo != soTienNo)
            {
                MessageBox.Show("Số phát sinh Nợ phải bằng số phát sinh Có.");
                kt = false;
            }
            if (kt == true)
            {
                db.ChungTus.Add(pt);
                try
                {
                    db.SaveChanges();
                    MessageBox.Show("Thêm mới thành công!");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

        void Reset()
        {
            txtNoiDung.Text = "";
            txtSoChungTuGoc.Text = "";
            GetMaPhieuChungTu();
            cbbNhaCungCap.SelectedIndex = -1;
            cbbNhanVien.SelectedIndex = -1;
            if (dgvPhieuTSCDCT.DataSource != null)
            {
                dgvPhieuTSCDCT.DataSource = null;
            }
            else
            {
                dgvPhieuTSCDCT.Rows.Clear();
            }
        }
        private void UpdateAmount(int index)
        {
            int counter;
            for (counter = 0; counter < (dgvPhieuTSCDCT.Rows.Count - 1); counter++)
            {
                if (dgvPhieuTSCDCT.Rows[counter].Cells["TaiKhoanNo"].Value == null &&
                    dgvPhieuTSCDCT.Rows[counter].Cells["TaiKhoanCo"].Value == null) continue;
                var tkNo = Convert.ToInt32(dgvPhieuTSCDCT.Rows[counter].Cells["TaiKhoanNo"].Value);
                var tkCo = Convert.ToInt32(dgvPhieuTSCDCT.Rows[counter].Cells["TaiKhoanCo"].Value);

                if (tkNo > 0 && tkCo > 0)
                {
                    if (index == 0)
                    {
                        MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                        dgvPhieuTSCDCT.Rows[counter].Cells["TaiKhoanNo"].Value = null;
                    }
                    else if (index == 1)
                    {
                        MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                        dgvPhieuTSCDCT.Rows[counter].Cells["TaiKhoanCo"].Value = null;
                    }
                }
                else
                {
                    if (index == 0 || index == 1)
                    {
                        if (tkNo == 211)
                        {
                            dgvPhieuTSCDCT.Rows[counter].Cells["TaiSanId"].ReadOnly = false;
                            dgvPhieuTSCDCT.Rows[counter].Cells["PhongBanId"].ReadOnly = false;
                            dgvPhieuTSCDCT.Rows[counter].Cells["SoTien"].ReadOnly = false;
                        }
                        else
                        {
                            dgvPhieuTSCDCT.Rows[counter].Cells["TaiSanId"].ReadOnly = true;
                            dgvPhieuTSCDCT.Rows[counter].Cells["PhongBanId"].ReadOnly = true;
                        }
                    }
                    if (index == 0 || index == 1)
                    {
                        if (tkNo == 133 || tkNo == 1331 || tkNo == 1332 || tkCo == 133 || tkCo == 1331 || tkCo == 1332 ||
                            tkCo == 621 || tkNo == 621)
                        {
                            dgvPhieuTSCDCT.Rows[counter].Cells["NhomThueHangHoaId"].ReadOnly = false;
                            dgvPhieuTSCDCT.Rows[counter].Cells["SoTien"].ReadOnly = false;
                        }
                        else
                        {
                            dgvPhieuTSCDCT.Rows[counter].Cells["NhomThueHangHoaId"].ReadOnly = true;
                        }
                    }
                }
            }
        }
        #endregion Metho


    }
}